package com.wanlian.netty.model;

import com.wanlian.json.JsonStringUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class DHTable {
    private Map<String, Address> iptables;

    public DHTable() {
        this.iptables = new HashMap<String, Address>();
    }

    public void add(Address address) {
        if (!this.iptables.containsKey(address.getPublickey())) {
            this.iptables.put(address.getPublickey(), address);
        }
    }

    public void sub(Address address) {
        if (this.iptables.containsKey(address.getPublickey())) {
            this.iptables.remove(address.getPublickey());
        }
    }

    public Map<String, Address> getIptables() {
        return iptables;
    }

    public void setIptables(Map<String, Address> iptables) {
        this.iptables = iptables;
    }

    public void sub(String publicKey) {
        if (this.iptables.containsKey(publicKey)) {
            this.iptables.remove(publicKey);
        }
    }

    /**
     * get a Random address
     *
     * @return address
     */
    public Address getRamdomOne() {
        String[] keys = iptables.keySet().toArray(new String[0]);
        Random random = new Random();
        //TODO：这里暂时写成0
        //String randomKey = keys[random.nextInt(keys.length)];
        String randomKey = keys[0];
        Address randomValue = iptables.get(randomKey);
        return randomValue;
    }

    public String toString() {
        return JsonStringUtil.writeValueAsString(this.iptables);
    }
}
